﻿using HotelManager.Common;
using HotelManager.Extensions;
using HotelManager.Models;
using HotelManager.Service;
using MaterialDesignColors;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HotelManager.ViewModels
{
    public class GuestViewModel: NavigationViewModel
    {
        private readonly IDialogHostService dialog;
        private readonly IRegionManager regionManager;
        private readonly IResideStateService resideStateService;
        private readonly IGuestService guestService;
        private readonly ITypeService typeService;
        private readonly IRoomService roomService;
        public GuestViewModel(IDialogHostService dialog, IContainerProvider provider, IGuestService _guestService) : base(provider)
        {
            regionManager = provider.Resolve<IRegionManager>();
            this.dialog = dialog;
            resideStateService = provider.Resolve<IResideStateService>();
            this.guestService = _guestService;
            typeService = provider.Resolve<ITypeService>();
            roomService = provider.Resolve<IRoomService>();
            ResideStateLists = new ObservableCollection<ResideState>();
            GuestDataLists = new ObservableCollection<GuestDetailData>();
            RoomTypeLists = new ObservableCollection<RoomTypeData>();
            RoomDetailLists = new ObservableCollection<RoomDetailData>();
            RoomIdLists = new ObservableCollection<RoomIdDetailData>();
            SearchCommand = new DelegateCommand(Search);
            ChangedResideStateCommand = new DelegateCommand<ResideState>(ChangeState);
            ExecuteCommand = new DelegateCommand<string>(Execute);
            SelectedCommand = new DelegateCommand<GuestDetailData>(Selected);
            DelCommand = new DelegateCommand<GuestDetailData>(Delete);
            CheckOutCommand = new DelegateCommand<GuestDetailData>(CheckOut);
            ChangedCommand = new DelegateCommand<RoomTypeData>(Change);
            ChangedRoomIdCommand = new DelegateCommand<RoomIdDetailData>(ChangedRoomId);
            SelectedResideStateStatus = new ResideState();
            SelectedRoomTypeStatus = new RoomTypeData();
            SelectedIdStatus = new RoomIdDetailData();
            GuestName = string.Empty;
            GetResideStateDataAsync();
            GetRoomTypeDataAsync();
           
        }
        public DelegateCommand<RoomTypeData> ChangedCommand { get; private set; }
        public DelegateCommand<RoomIdDetailData> ChangedRoomIdCommand { get; private set; }
        private void Change(RoomTypeData roomTypeDatas)
        {
            SelectedRoomTypeStatus = roomTypeDatas;
            GetRoomData(SelectedRoomTypeStatus == null?0: SelectedRoomTypeStatus.RoomTypeId, 1, 0, 0);
        }
        private void ChangedRoomId(RoomIdDetailData roomIdDetailDatas)
        {
            SelectedIdStatus = roomIdDetailDatas;
        }
        public DelegateCommand<GuestDetailData> SelectedCommand { get; private set; }
        public DelegateCommand<GuestDetailData> DelCommand { get; private set; }
        public DelegateCommand<GuestDetailData> CheckOutCommand { get; private set; }
        private async void CheckOut(GuestDetailData obj)
        {
            var dialogResult = await dialog.Question("温馨提示", $"确认结账吗：{obj.guestId}?");
            if (dialogResult.Result != ButtonResult.OK) return;
            var deleteResult = guestService.CheckOut(new GuestDetailData() { guestId = obj.guestId });
            if (deleteResult!=null)
            {
                var model = GuestDataLists.FirstOrDefault(o => o.guestId.Equals(obj.guestId));
                GetData(GuestName, SelectedResideStateStatus.resideStateId, 0, 0);
            }
        }
        private async void Delete(GuestDetailData obj)
        {
            var dialogResult = await dialog.Question("温馨提示", $"确认删除客房编号：{obj.roomId}?");
            if (dialogResult.Result != ButtonResult.OK) return;
            var deleteResult = guestService.Delete(new GuestDetailData() { guestId = obj.guestId });
            if (deleteResult.success)
            {
                var model = GuestDataLists.FirstOrDefault(o => o.guestId.Equals(obj.guestId));
                if (model != null)
                    GuestDataLists.Remove(model);
            }
        }
        private void Selected(GuestDetailData guestDetailData)
        {
            try
            {
                UpdateLoading(true);
                var memoResult = guestService.GetFirstOrDefaultAsync(guestDetailData.guestId);
                if (memoResult is not null)
                {
                    CurrentReturnDto = new GuestReturnOneData() { guestId = memoResult.guestId,
                        guestName=memoResult.guestName,guestNum=memoResult.guestNum,deposit=memoResult.deposit,totalMoney=memoResult.totalMoney, 
                        identityId = memoResult.identityId, phone = memoResult.phone, roomId = memoResult.roomId,room= memoResult.room ,
                        resideDate=memoResult.resideDate,leaveDate=memoResult.leaveDate,resideStateId=memoResult.resideStateId
                    };
                    SelectedRoomTypeStatus = new RoomTypeData() { RoomTypeId = guestDetailData.room.roomType.RoomTypeId, RoomTypeName = guestDetailData.room.roomType.RoomTypeName };
                    SelectedIdStatus = new RoomIdDetailData() { roomId = CurrentReturnDto.roomId, roomIdName = CurrentReturnDto.roomId.ToString() };
                    Date = DateTime.Parse(memoResult.resideDate).ToString("yyyy-MM-dd");
                    Time = DateTime.Parse(memoResult.resideDate).ToString("HH:mm:ss");
                    IsRightDrawerOpen = true;
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                UpdateLoading(false);
            }
        }
        public DelegateCommand<string> ExecuteCommand { get; private set; }
        private void Execute(string Operater)
        {
            switch (Operater)
            {
                case "Add":
                    OpenDraw();
                    break;
                case "Save":
                    Save();
                    break;
            }
        }
        private void OpenDraw()
        {
            CurrentReturnDto = new GuestReturnOneData();
            Date = string.Empty;
            Time = string.Empty;
            IsRightDrawerOpen = true;
        }
        private async void Save()
        {
            if (string.IsNullOrWhiteSpace(CurrentReturnDto.guestName) || string.IsNullOrWhiteSpace(CurrentReturnDto.phone))
                return;
            UpdateLoading(true);
            try
            {
                if (CurrentReturnDto.guestId > 0)
                {
                    var updateResult = guestService.Update(CurrentReturnDto);
                    if (updateResult.success)
                    {
                        var todo = GuestDataLists.FirstOrDefault(t => t.guestId == CurrentDto.guestId);
                        if (todo != null)
                        {
                            GetData(GuestName, 0, 0, 0);
                        }
                    }
                    IsRightDrawerOpen = false;
                }
                else
                {
                    CurrentReturnDto.resideDate = DateTime.Parse(Date + " " + Time).ToString();
                    CurrentReturnDto.room = SelectedRoomTypeStatus;
                    CurrentReturnDto.roomId = SelectedIdStatus.roomId;
                    var addResult = guestService.Add(CurrentReturnDto);
                    if (addResult.success)
                    {
                        //RoleLists.Add(addResult.Result);
                        GetData(GuestName, 0, 0, 0);
                        IsRightDrawerOpen = false;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally { UpdateLoading(false); }
        }
        private string date;
        public string Date
        {
            get { return date; }
            set { date = value; RaisePropertyChanged(); }
        }
        private string time;
        public string Time
        {
            get { return time; }
            set { time = value; RaisePropertyChanged(); }
        }
        private GuestDetailData currentDto;

        public GuestDetailData CurrentDto
        {
            get { return currentDto; }
            set { currentDto = value; RaisePropertyChanged(); }
        }
        private GuestReturnOneData currentReturnDto;
        public GuestReturnOneData CurrentReturnDto
        {
            get { return currentReturnDto; }
            set { currentReturnDto = value; RaisePropertyChanged(); }
        }
        private bool isRightDrawerOpen;

        public bool IsRightDrawerOpen
        {
            get { return isRightDrawerOpen; }
            set { isRightDrawerOpen = value; RaisePropertyChanged(); }
        }
        public DelegateCommand SearchCommand { get; private set; }
        private void Search()
        {
            int stateId = SelectedResideStateStatus == null ? 0 : SelectedResideStateStatus.resideStateId;
            GetData(GuestName, stateId, 0, 10);
        }
        public ObservableCollection<ResideState> resideStateLists;
        public ObservableCollection<ResideState> ResideStateLists
        {
            get { return resideStateLists; }
            set { resideStateLists = value; RaisePropertyChanged(); }
        }
        public ObservableCollection<GuestDetailData> guestDataLists;
        public ObservableCollection<GuestDetailData> GuestDataLists
        {
            get { return guestDataLists; }
            set { guestDataLists = value; RaisePropertyChanged(); }
        }
        private string guestName;
        public string GuestName
        {
            get { return guestName; }
            set 
            { 
                guestName = value;
                RaisePropertyChanged();
            }
        }
        private int selectedResideStateIndex;

        public int SelectedResideStateIndex
        {
            get { return selectedResideStateIndex; }
            set 
            {
                selectedResideStateIndex = value;
                RaisePropertyChanged();
            }
        }
        private int selectedRoomTypeIndex;

        public int SelectedRoomTypeIndex
        {
            get { return selectedRoomTypeIndex; }
            set
            {
                selectedRoomTypeIndex = value;
                RaisePropertyChanged();
            }
        }
        private int selectedRoomIdIndex;

        public int SelectedRoomIdIndex
        {
            get { return selectedRoomIdIndex; }
            set
            {
                selectedRoomIdIndex = value;
                RaisePropertyChanged();
            }
        }
        public DelegateCommand<ResideState> ChangedResideStateCommand { get; private set; }
        private ResideState selectedResideStateStatus;
        public ResideState SelectedResideStateStatus
        {
            get { return selectedResideStateStatus; }
            set
            {
                selectedResideStateStatus = value;
                RaisePropertyChanged();
            }
        }
        private void ChangeState(ResideState stateDatas)
        {
            SelectedResideStateStatus = stateDatas;
        }
        private void GetResideStateDataAsync()
        {
            var resideStateListResult = resideStateService.GetAll();
            if (resideStateListResult.Any())
            {
                ResideStateLists.Clear();
                ResideStateLists.Add(new ResideState() { resideStateId = 0, resideStateName = "请选择角色" });
                foreach (var item in resideStateListResult)
                {
                    ResideStateLists.Add(item);
                }
            }

        }
        public ObservableCollection<RoomTypeData> roomTypeLists;
        public ObservableCollection<RoomTypeData> RoomTypeLists
        {
            get { return roomTypeLists; }
            set { roomTypeLists = value; RaisePropertyChanged(); }
        }
        public ObservableCollection<RoomDetailData> roomDetailLists;
        public ObservableCollection<RoomDetailData> RoomDetailLists
        {
            get { return roomDetailLists; }
            set { roomDetailLists = value; RaisePropertyChanged(); }
        }
        public ObservableCollection<RoomIdDetailData> roomIdLists;
        public ObservableCollection<RoomIdDetailData> RoomIdLists
        {
            get { return roomIdLists; }
            set { roomIdLists = value; RaisePropertyChanged(); }
        }
        public RoomTypeData selectedRoomTypeStatus;
        public RoomTypeData SelectedRoomTypeStatus
        {
            get { return selectedRoomTypeStatus; }
            set
            {
                selectedRoomTypeStatus = value;
                RaisePropertyChanged();
            }
        }
        public RoomIdDetailData selectedIdStatus;
        public RoomIdDetailData SelectedIdStatus
        {
            get { return selectedIdStatus; }
            set
            {
                selectedIdStatus = value;
                RaisePropertyChanged();
            }
        }
        private void GetRoomData(int roomTypeId, int roomStateId, int pageIndex, int pageSize)
        {
            UpdateLoading(true);
            var roomListResult = roomService.GetAll(roomTypeId, roomStateId, pageIndex, pageSize);
            if (roomListResult is not null && roomListResult.count > 0)
            {

                //RoomDetailLists.Clear();
                RoomIdLists.Clear();
                RoomIdLists.Add(new RoomIdDetailData() { roomId=0,roomIdName="请选择房间"});
                foreach (var item in roomListResult.data)
                {
                    RoomIdLists.Add(new RoomIdDetailData() { roomId=item.roomId,roomIdName=item.roomId.ToString()});
                }
                
            }
            UpdateLoading(false);
        }
        private async void GetRoomTypeDataAsync()
        {
            var roomTypeListResult = await typeService.GetAllAsync();
            if (roomTypeListResult.Any())
            {
                RoomTypeLists.Clear();
                RoomTypeLists.Add(new RoomTypeData() { RoomTypeId =0, RoomTypeName = "请选择角色" });
                foreach (var item in roomTypeListResult)
                {
                    RoomTypeLists.Add(item);
                }
            }

        }
        private void GetData(string guestName, int resideStateId, int pageIndex, int pageSize)
        {
            UpdateLoading(true);
            var roomListResult = guestService.GetAll(guestName, resideStateId, pageIndex, pageSize);
            if (roomListResult is not null && roomListResult.count > 0)
            {
                GuestDataLists.Clear();
                foreach (var item in roomListResult.data)
                {

                    GuestDataLists.Add(item);
                }
            }
            UpdateLoading(false);
        }
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);

            //获取role
            
            GetData(GuestName, SelectedResideStateStatus.resideStateId, 0, 10);
        }
    }
}
